package com.itheima.case2.web;

import com.itheima.case2.pojo.po.User;
import com.itheima.case2.pojo.vo.Result;
import com.itheima.case2.service.UserServiceImpl_1;
import com.itheima.case2.utils.BaseController;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String htmlInputCode = request.getParameter("code");
        String sessionCheckCode = (String) request.getSession().getAttribute("checkcode");
        User user = new User();
        user.setUsername(username);
        user.setPassword(pwd);
        UserServiceImpl_1 userService = new UserServiceImpl_1();
        User u = userService.login(user);
        if(u != null & sessionCheckCode.equalsIgnoreCase(htmlInputCode)){

            //创建Result对象存储返回信息
            Result result = new Result(true, "恭喜你登录成功");
            //响应给前端
            BaseController.printResult(response, result);

        }else{
            if (sessionCheckCode.equalsIgnoreCase(htmlInputCode)){
                //创建Result对象存储返回信息
                Result result = new Result(false, "验证码错误");
                //响应给前端
                BaseController.printResult(response, result);

            }else{
                //创建Result对象存储返回信息
                Result result = new Result(false, "用户名或密码错误");
                //响应给前端
                BaseController.printResult(response, result);
            }

        }
    }
}
